﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="../Javascript/jquery-1.8.0.min.js"></script>
</head>
<body>
    <div id="d1"></div>
</body>
</html>
<script type="text/javascript">
    var CreateTable = function (container) {
        this._container = $(container);
        this._tab = $("<table></table>");
        this._cols = new Array();

        this.Check = function (data) {
            if (data.length == 0 || data == null) {
                return false;
            }
            return true;
        }

        this.GetCols = function (data) {
            this._cols.length = 0;
            if (this.Check(data)) {
                for (var i in data[0]) {
                    this._cols.push(i);
                }
            } else {
                this._cols.length == 0;
                return;
            }
        }

        //需要转换列名的json资源:[{Key:'Id',Value:'编号'},{Key:'Name',Value:'姓名'}]
        //colJson 允许为空
        this.RenderHead = function (data,colJson) {
            this.GetCols(data);
            var _tabHead = "<tr>";
            if (colJson == null) {
                for (var i = 0; i < this._cols.length; i++) {
                    _tabHead += "<td>" + this._cols[i], colJson + "</td>";
                }
                _tabHead += "</tr>";
            }
            else {
                for (var i = 0; i < this._cols.length; i++) {
                    _tabHead += "<td>" + this.ConvertHead(this._cols[i], colJson) + "</td>";
                }
                _tabHead += "</tr>";
            }
            this._tab.append($(_tabHead));
        }
        
        //data:[{id:'1',name:'A'},{id:'1',name:'A'}]
        this.RenderBody = function (data) {
            //render body
            var _tabBody = "";
            for (var i = 0; i < data.length; i++) {
                _tabBody += "<tr>";
                for (var j = 0; j < this._cols.length; j++) {
                    _tabBody += "<td>" + data[i][this._cols[j]] + "</td>";
                }
                _tabBody += "</tr>";
            }
            this._tab.append($(_tabBody));

            this._container.append(this._tab);
        }

        //转换表头为中文
        this.ConvertHead = function (colKey, colJson) {
            var result = "";
            for (var i = 0; i < colJson.length; i++) {
                if (colKey == colJson[i].Key) {
                    result = colJson[i].Value;
                }
            }
            return result;
        }
    }

    var colData = [{ Key: 'Id', Value: '编号' }, { Key: 'Name', Value: '姓名' }, { Key: 'Age', Value: '性别' }];
    var data = [{ Id: '1', Name: 'A', Age: 12 }, { Id: '1', Name: 'A', Age: 13 }];
    var t = new CreateTable($("#d1"));
    t.RenderHead(data,colData);
    t.RenderBody(data);
</script>
